// pages/groupOrderDetail/groupOrderDetail.js
const app = getApp()
var util = require("../../utils/utils.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timer: '',// 计时器
    isPopupHide: true,
    isGrouper: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.pay) {
      this.setData({ isPopupHide: false})
    }
    this.getUserInfo(options);
  },
  initData: function(options) {
    var orderNo = options.orderNo;
    var groupNo = options.groupNo;
    if (orderNo) this.groupOrderDetail(orderNo);
    if (groupNo) this.groupDetail(groupNo);
  },
  popupClose: function() {
    this.setData({
      isPopupHide: true
    })
  },
  groupOrderDetail: function(orderNo) {
    wx.request({
      url: app.httpUrl + '/pay/groupOrderDetail/' + orderNo,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        if (res.data.code == '000') {
          var groupOrder = res.data.data.groupOrder;
          groupOrder.startDate = util.formatDate(groupOrder.startDate, 'M月D日');
          groupOrder.endDate = util.formatDate(groupOrder.endDate, 'M月D日');
          for (var i in groupOrder.memberList) {
            groupOrder.memberList[i].payDate = util.formatDate(groupOrder.memberList[i].payCallbackTime, 'Y.M.D');
          } 
          var yulist = [];
          for (var i = 0; i < 5 - groupOrder.memberList.length; i++) {
            yulist.push(i);
          }
          this.setData({
            productOrder: res.data.data.productOrder,
            groupOrder: groupOrder,
            yulist: yulist,
            groupNo: groupOrder.groupNo,
            isGrouper: groupOrder.groupUserId == app.globalData.appUser.userInfo.id ? true : false
          });
          this.groupTime();
        }
      }
    })
  },
  groupDetail: function (groupNo) {
    wx.request({
      url: app.httpUrl + '/pay/groupResult/' + groupNo,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        if (res.data.code == '000') {
          var groupOrder = res.data.data;
          groupOrder.startDate = util.formatDate(groupOrder.startDate, 'M月D日');
          groupOrder.endDate = util.formatDate(groupOrder.endDate, 'M月D日');
          for (var i in groupOrder.memberList) {
            groupOrder.memberList[i].payDate = util.formatDate(groupOrder.memberList[i].payCallbackTime, 'Y.M.D');
          }
          var yulist = [];
          for (var i = 0; i < 5 - groupOrder.memberList.length; i++) {
            yulist.push(i);
          }
          this.setData({
            groupOrder: groupOrder,
            yulist: yulist,
            groupNo: groupOrder.groupNo,
            isGrouper: groupOrder.groupUserId == app.globalData.appUser.userInfo.id ? true : false
          });
          this.groupTime();
        }
      }
    })
  },
  joinGroup: function() {
    wx.navigateTo({
      url: '/pages/groupOrderApply/groupOrderApply?groupNo=' + this.data.groupNo + '&productId=' + this.data.groupOrder.productId
    })
  },
  createGroup: function () {
    wx.navigateTo({
      url: '/pages/groupOrderApply/groupOrderApply?productId=' + this.data.groupOrder.productId
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.appUser.userInfo.nickName + '邀请您参团' + this.data.groupOrder.courseName +' From陶学趣',
      path: this.data.groupOrder.groupStatus == '002' ? '/pages/groupOrderDetail/groupOrderDetail?groupNo=' + this.data.groupOrder.groupNo : '/pages/programme/programme?productid=' + this.data.groupOrder.productId,
      imageUrl: app.imgUrl + this.data.groupOrder.courseImg, //这是我的图片路径
      success: function (res) {
        //转发成功
      }
    }
  },
  getUserInfo: function (options) {
    let that = this;
    if (app.globalData.appUser != null) {
      this.initData(options);
      return;
    }
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.httpUrl + '/common/getUserInfo',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            method: "POST",
            success: function (res) {
              if (res.data.code == '000') {
                app.globalData.appUser = res.data.data;
                app.globalData.openid = res.data.data.openid;
                that.initData(options);
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  groupTime: function(end) {
    let that = this;
    var end = that.data.groupOrder.invalidTime;
    that.setData({
      timer: setInterval(function () {
        var now = new Date().getTime();
        var leftTime = end - now;
        //定义变量 d,h,m,s保存倒计时的时间
        var downtime = {}, d, h, m, s;
        if (leftTime >= 0) {
          downtime.d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
          h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
          downtime.h = h < 10 ? '0' + h : h;
          m = Math.floor(leftTime / 1000 / 60 % 60);
          downtime.m = m < 10 ? '0' + m : m;
          s = Math.floor(leftTime / 1000 % 60);
          downtime.s = s < 10 ? '0' + s : s;
          that.setData({ downtime: downtime });
        }else {
          clearInterval(that.data.timer);
        }
      }, 1000)
    })
  },
  paySign: function () {
    wx.request({
      url: app.httpUrl + '/pay/sign',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        orderNo: this.data.productOrder.orderNo
      },
      method: "POST",
      success: (res) => {
        var signData = res.data.data;
        this.payment(signData);
      }
    })
  },
  payment: function (signData) {
    var thiz = this;
    wx.requestPayment({
      'timeStamp': signData.timeStamp,
      'nonceStr': signData.nonceStr,
      'package': signData.packages,
      'signType': 'MD5',
      'paySign': signData.paySign,
      success: function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
        thiz.groupOrderDetail(signData.orderNo);
      },
      fail: function (res) {
        //wx.showToast({ title: '支付失败', icon: 'none', duration: 2000 });
      },
      'complete': function (res) {
        console.log(res);
      }
    })
  }
})